package com.qst.express.controller.wx;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.qst.commonUtils.express.RandomUtil;
import com.qst.commonUtils.result.R;
import com.qst.express.entity.Express;
import com.qst.express.entity.User;
import com.qst.express.entity.vo.TableExpress;
import com.qst.express.service.CourierService;
import com.qst.express.service.ExpressService;
import com.qst.express.utils.DateFormatUtil;
import com.qst.express.utils.JSONUtil;
import com.qst.express.utils.UserUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @author:CoolTiger
 * @title: WxExpressController
 * @projectName springboot-e
 * @description: TODO
 * @date:2022/10/13/15:37:58
 **/
@Api(description = "微信端-快递管理")
@RestController
@RequestMapping("/e/wx")
@CrossOrigin
public class WxExpressController {
    @Autowired
    private ExpressService expressService;
    @Autowired
    private CourierService courierService;
    /**
     * 查询快递月排名
     * @return
     */
    @GetMapping("/getRankMonth")
    public R getRankMonth() {
        List<Express> rankMonth = expressService.rankByMonth();
        for (Express express : rankMonth)   {
            System.out.println(express);
        }
        return R.ok().code(0).data("rankMonth",rankMonth);
    }

    /**
     * 查询年快递排行
     * @return
     */
    @GetMapping("/getRankYear")
    public R getRankYear() {
        List<Express> rankYear = expressService.rankByYear();

        return R.ok().code(0).data("rankYear",rankYear);
    }

    /**
     * 查询总快递排行
     * @return
     */
    @GetMapping("/getRankAll")
    public R getRankAll() {
        List<Express> rankAll = expressService.rankByAll();

        return R.ok().code(0).data("rankAll",rankAll);
    }
    /**
     * 通过单号查询快递信息
     * @param request
     * @param number
     * @return
     */
    @GetMapping("/findExpressByNumber/{number}")
    public String findExpressByNumber(HttpServletRequest request, @PathVariable(value = "number") String number) {
        Express express1 = expressService.findByNumber(number);
        System.out.println("--------------"+express1);
        List<Express> list = new ArrayList<>();
        List<TableExpress> list2 = new ArrayList<>();
        if (express1 != null) {
            list.add(express1);
            //转换格式
            for (Express e : list) {
                String inTime = DateFormatUtil.format(e.getIntime());
                String outTime = e.getOuttime() == null ? "未出库" : DateFormatUtil.format(e.getOuttime());
                String status = e.getStatus() == 0 ? "待取件" : "已取件";
                String code = e.getCode() == null ? "已取件" : e.getCode();
                TableExpress e2 = new TableExpress(e.getId(), e.getNumber(), e.getUsername(), e.getUserphone(), e.getCompany(), code, inTime, outTime, status, e.getSysphone());
                list2.add(e2);
            }

        }
        R r = new R();

        if (list.size() == 0) {
            r.setCode(-1);
            r.setMessage("查询失败");
        } else {
            r.setCode(0);
            r.setMessage("查询成功");
            Stream<TableExpress> status0Express = list2.stream().filter(express -> {
                if (express.getStatus().equals("待取件")) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1, o2) -> {
                long o1Time = DateFormatUtil.toTime(o1.getInTime());
                long o2Time = DateFormatUtil.toTime(o2.getInTime());
                return (int) (o1Time - o2Time);
            });
            Stream<TableExpress> status1Express = list2.stream().filter(express -> {
                if (express.getStatus().equals("已取件")) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1, o2) -> {
                long o1Time = DateFormatUtil.toTime(o1.getInTime());
                long o2Time = DateFormatUtil.toTime(o2.getInTime());
                return (int) (o1Time - o2Time);
            });

            Object[] s0 = status0Express.toArray();
            Object[] s1 = status1Express.toArray();
            Map data = new HashMap<>();
            data.put("status0", s0);
            data.put("status1", s1);
            r.setData(data);
            // return R.ok().data("data",data);
        }
        String json = JSONUtil.toJSON(r);
        return json;
    }

    /**
     * 快递确认收货
     * @param code
     * @return
     */
    @GetMapping("/e/wx/updateExpressStatus.do")
    public R updateExpressStatus(@RequestParam("code") String code){
        boolean flag = expressService.updateStatus(code);
        if (flag){
            return R.ok().code(0).message("取件成功");
        }else {
            return R.ok().code(-1).message("取件失败，请用户更新二维码");
        }
    }
    /**
     * 通过用户手机展示《我的快件》-历史所有快递
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/findExpressByUserPhone")
    @ResponseBody
    public String findByUserPhone(HttpServletRequest request, HttpServletResponse response) {
        // 获取用户手机号码
        User wxUser = UserUtil.getWxUser(request.getSession());
        String userphone = wxUser.getUphone();
        List<Express> list = expressService.findByUserPhone(userphone);

        List<TableExpress> list2 = null;
        if (list != null) {
            list2 = new ArrayList<>();
            //转换格式
            for (Express e : list) {
                String inTime = DateFormatUtil.format(e.getIntime());
                String outTime = e.getOuttime() == null ? "未出库" : DateFormatUtil.format(e.getOuttime());
                String status = e.getStatus() == 0 ? "待取件" : "已取件";
                String code = e.getCode() == null ? "已取件" : e.getCode();
                TableExpress e2 = new TableExpress(e.getId(), e.getNumber(), e.getUsername(), e.getUserphone(), e.getCompany(), code, inTime, outTime, status, e.getSysphone());
                list2.add(e2);
            }


        }
        R r = new R();

        if (list.size() == 0) {
            r.setCode(-1);
            r.setMessage("查询失败");
        } else {
            r.setCode(0);
            r.setMessage("查询成功");
            Stream<TableExpress> status0Express = list2.stream().filter(express -> {
                if (express.getStatus().equals("待取件")) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1, o2) -> {
                long o1Time = DateFormatUtil.toTime(o1.getInTime());
                long o2Time = DateFormatUtil.toTime(o2.getInTime());
                return (int) (o1Time - o2Time);
            });
            Stream<TableExpress> status1Express = list2.stream().filter(express -> {
                if (express.getStatus().equals("已取件")) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1, o2) -> {
                long o1Time = DateFormatUtil.toTime(o1.getInTime());
                long o2Time = DateFormatUtil.toTime(o2.getInTime());
                return (int) (o1Time - o2Time);
            });

            Object[] s0 = status0Express.toArray();
            Object[] s1 = status1Express.toArray();
            Map data = new HashMap<>();
            data.put("status0", s0);
            data.put("status1", s1);
           r.setData(data);
           // return R.ok().data("data",data);
        }
        String json = JSONUtil.toJSON(r);
        return json;
    }

    /**
     * 微信端-快递员通过用户手机查询历史所有快递
     * @param request
     * @return
     */
    @GetMapping("/findExpressHistoryByUserPhone")
    @ResponseBody
    public String findExpressHistoryByUserPhone(HttpServletRequest request,@RequestParam("userPhone") String userPhone) {
        R r = new R();
        if (StringUtils.isEmpty(userPhone) || "".equals(userPhone)){
            r.setCode(-2);
            r.setMessage("请输入手机号码");
            String json = JSONUtil.toJSON(r);
            return json;
        }
        List<Express> list = expressService.findByUserPhone(userPhone);
        List<TableExpress> list2 = null;
        if (list != null) {
            list2 = new ArrayList<>();
            //转换格式
            for (Express e : list) {
                String inTime = DateFormatUtil.format(e.getIntime());
                String outTime = e.getOuttime() == null ? "未出库" : DateFormatUtil.format(e.getOuttime());
                String status = e.getStatus() == 0 ? "待取件" : "已取件";
                String code = e.getCode() == null ? "已取件" : e.getCode();
                TableExpress e2 = new TableExpress(e.getId(), e.getNumber(), e.getUsername(), e.getUserphone(), e.getCompany(), code, inTime, outTime, status, e.getSysphone());
                list2.add(e2);
            }


        }


        if (list.size() == 0) {
            r.setCode(-1);
            r.setMessage("用户无快递信息");
        } else {
            r.setCode(0);
            r.setMessage("查询成功");
            Stream<TableExpress> status0Express = list2.stream().filter(express -> {
                if (express.getStatus().equals("待取件")) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1, o2) -> {
                long o1Time = DateFormatUtil.toTime(o1.getInTime());
                long o2Time = DateFormatUtil.toTime(o2.getInTime());
                return (int) (o1Time - o2Time);
            });
            Stream<TableExpress> status1Express = list2.stream().filter(express -> {
                if (express.getStatus().equals("已取件")) {
                    return true;
                } else {
                    return false;
                }
            }).sorted((o1, o2) -> {
                long o1Time = DateFormatUtil.toTime(o1.getInTime());
                long o2Time = DateFormatUtil.toTime(o2.getInTime());
                return (int) (o1Time - o2Time);
            });

            Object[] s0 = status0Express.toArray();
            Object[] s1 = status1Express.toArray();
            Map data = new HashMap<>();
            data.put("status0", s0);
            data.put("status1", s1);
            r.setData(data);
            // return R.ok().data("data",data);
        }
        String json = JSONUtil.toJSON(r);
        return json;
    }
    /**
     * 通过手机号码查询未取件快递
     * @param request
     * @param userPhone
     * @return
     */
    @GetMapping("/userExpressList")
    public String expressList(HttpServletRequest request,@RequestParam("userPhone") String userPhone){

        List<Express> list = expressService.findByUserPhoneAndStatus(userPhone, 0);

        List<TableExpress> list2 = new ArrayList<>();
        //转换格式
        for (Express e : list) {
            String inTime = DateFormatUtil.format(e.getIntime());
            String outTime = e.getOuttime() == null ?"未出库": DateFormatUtil.format(e.getIntime());
            String status= e.getStatus() == 0 ?"待取件" :"已取件";
            String code = e.getCode() == null ? "已取件":e.getCode();
            TableExpress e2 = new TableExpress(e.getId(),e.getNumber(),e.getUsername(),e.getUserphone(),e.getCompany(),code,inTime,outTime,status,e.getSysphone());
            list2.add(e2);
        }
        R r = new R();
        if (list2.size()==0){
            r.setCode(-1);
            r.setMessage("为查询到快递");
        }else {
            // msg.setData(list2);
            r.setCode(0);
            r.setMessage("查询成功");
            r.setData2(list2);
        }
        return JSONUtil.toJSON(r);
    }
    /**
     * 根据取件码查询快递信息
     * @param request
     * @param code
     * @return
     */
    @GetMapping("/findExpressByCode")
    public String findExpressByCode(HttpServletRequest request,@RequestParam("code") String code){
        Express e = expressService.findByCode(code);
        TableExpress e2 = null;
        if (e!=null){
            e2 = new TableExpress(e.getId(), e.getNumber(), e.getUsername(), e.getUserphone(), e.getCompany(), e.getCode(), DateFormatUtil.format(e.getIntime()), e.getOuttime()==null?"未出库":DateFormatUtil.format(e.getOuttime()),e.getStatus()==0?"待取件":"已取件", e.getSysphone());
        }


        R r = new R();

        if (e == null){
            r.setCode(-1);
            r.setMessage("取件码不存在");
        }else {
            r.setCode(0);
            r.setMessage("查询成功");
            r.setData2(e2);
        }
        return JSONUtil.toJSON(r);


    }
    /**
     * 根据取件码取件：更新快递信息
     * @param request
     * @param code
     * @return
     */
    @GetMapping("/updateExpressStatus")
    public String updateExpressStatus(HttpServletRequest request,@RequestParam("code") String code){

        // 获取用户手机号码
        User wxUser = UserUtil.getWxUser(request.getSession());
        String userphone = wxUser.getUphone();

        boolean flag = expressService.updateStatus(code);
        R r = new R();
        if (flag){
            r.setCode(0);
            r.setMessage("取件成功");
            boolean flag2 = courierService.addDelivery(userphone);
        }else {
            r.setCode(-1);
            r.setMessage("取件失败，请用户更新二维码");
        }
        return JSONUtil.toJSON(r);
    }

    /**
     * 微信端-快递员录入快递
     * @param express
     * @param request
     * @return
     */
    @PostMapping("/addExpress")
    public R addExpress(@RequestBody(required = false) Express express,HttpServletRequest request){

        if(StringUtils.isEmpty(express.getNumber())||StringUtils.isEmpty(express.getUserphone())|| StringUtils.isEmpty(express.getUsername())){
            return R.error().code(-1).message("请完善信息");
        }

        String uphone = UserUtil.getWxUser(request.getSession()).getUphone();

        String userphone = express.getUserphone();
        String number = express.getNumber();
        boolean isExsitNumber = expressService.isExsitNumber(number);
        boolean isExsitUserPhone = expressService.isExsitUserPhone(userphone);
        // 判断单号是否重复
        if (isExsitNumber ){
            return  R.error().code(-1).message("单号已存在");
        }
        // 判断手机号是否重复
        if (isExsitUserPhone){
            return  R.error().code(-1).message("手机号已存在");
        }
        // 录入快递
        boolean flag = expressService.saveExpress(express,uphone);
        if (flag) {
            return R.ok().code(0).message("快递录入成功");
        }
        return R.error().code(-1).message("快递录入失败");

    }


    

}
